package impl.service;

import tools.FilePath;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AudioServer {
    private ServerSocket serverSocket = null;
    public AudioServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("音乐播放服务器启动!");

        while (true) {
            Socket clientSocket = serverSocket.accept();
            ExecutorService pool = Executors.newFixedThreadPool(10);
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }

    public void processConnection(Socket clientSocket) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
            String filePath = reader.readLine(); // 读取客户端发送的文件路径
            String url = FilePath.URL + filePath + ".wav";
            File audioFile = new File(url); // 通过路径获取音频文件
            FileInputStream fis = new FileInputStream(audioFile);
            BufferedInputStream bis = new BufferedInputStream(fis);
            OutputStream os = clientSocket.getOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}